package com.luoyuanxiangvip.core.service.impl;

import com.luoyuanxiangvip.core.entity.BizComment;
import com.luoyuanxiangvip.core.entity.MailDetail;
import com.luoyuanxiangvip.core.entity.SysTemplate;
import com.luoyuanxiangvip.common.enums.TemplateKeyEnum;
import com.luoyuanxiangvip.core.service.IMailService;
import com.luoyuanxiangvip.core.service.ISysTemplateService;
import com.luoyuanxiangvip.common.utils.FreeMarkerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  邮件发送
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/6/15
 */
@Slf4j
@Service
public class MailServiceImpl implements IMailService {

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private ISysTemplateService iSysTemplateService;

    @Value("${spring.mail.username}")
    private String from;
    /**
     * 普通的发送
     *
     * @param mailDetail mailDetail
     */
    @Override
    @Async
    public void send(MailDetail mailDetail) {
        sendMessage(mailDetail, from);
    }

    /**
     * 发送到管理员的评论通知
     *
     * @param comment 评论
     */
    @Override
    @Async
    public void sendToAdmin(BizComment comment) {
        SysTemplate template = iSysTemplateService.getTemplate(TemplateKeyEnum.TM_NEW_COMMENT);
        String temXml = template.getRefValue();
        Map<String, Object> map = new HashMap<>(1);
        map.put("comment", comment);
        String mailContext = FreeMarkerUtil.template2String(temXml, map, true);
        String subject = "有新的评论消息";
        String adminEmail = "luoyuanxiang0606@foxmail.com";
        MailDetail mailDetail = new MailDetail(subject, adminEmail, "罗远祥", mailContext);
        send(mailDetail);
    }

    private void sendMessage(MailDetail detail, String from) {
        log.info("Start to send html email for [{}({})]", detail.getToUsername(), detail.getToMailAddress());
        if (StringUtils.isEmpty(detail.getToMailAddress())) {
            log.warn("邮件接收者为空！");
            return;
        }
        MimeMessage message = null;
        try {
            message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 创建邮件发送者地址
            InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText("网站管理员") + "<" + from + ">");
            helper.setFrom(fromAddress);
            // 创建邮件接收者地址
            InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText(detail.getToMailAddress()) + "<" + detail.getToMailAddress() + ">");
            helper.setTo(toAddress);
            helper.setSubject(detail.getSubject());
            // 第二个参数指定发送的是HTML格式
            helper.setText(detail.getContent(), detail.isHtml());
            if (detail.getCc() != null && detail.getCc().length > 0) {
                helper.setCc(detail.getCc());
            }
            if (detail.isExitFile()) {
                List<String> filePaths = detail.getFilePaths();
                filePaths.forEach(filePath -> {
                    // 附件 ：注意项目路径问题，自动补用项目路径
                    FileSystemResource file = new FileSystemResource(new File(filePath));
                    try {
                        helper.addAttachment("图片.jpg", file);
                    } catch (MessagingException e) {
                        log.error("添加附件发生异常", e);
                    }
                });
            }
            javaMailSender.send(message);
        } catch (UnsupportedEncodingException | MessagingException e) {
            log.error("Failed to send E-mail. e [{}]", e.getMessage());
        }
    }
}
